﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.BasePages;
using System.IO;
using Core.Module;
using umbraco.cms.presentation.Trees;
using Core.Module.Interfaces.Model;

namespace Module.MultiSiteFields.DataServices
{
    public class TreePickerService : System.Web.IHttpHandler
    {
        public static void Authorize()
        {
            if (!BasePage.ValidateUserContextID(BasePage.umbracoUserContextID))
            {
                throw new Exception("Client authorization failed. User is not logged in");
            }
        }


        public string GetInitAppTreeData(data d)
        {

            BaseTree tree = TreeDefinitionCollection.Instance.FindTree(d.treeType).CreateInstance();

            tree.ShowContextMenu = d.showContextMenu;
            tree.IsDialog = d.isDialog;
            tree.DialogMode = d.dialogMode;
            tree.NodeKey = d.nodeKey == "null" ? "" : d.nodeKey;
            int treeid = -1;
            tree.id = int.TryParse(tree.NodeKey, out treeid) ? treeid : -1;
            tree.FunctionToCall = string.IsNullOrEmpty(d.functionToCall) ? "" : d.functionToCall;


            int curNodeKey;
            XmlTree xtree = new XmlTree();
            if (int.TryParse(tree.NodeKey, out curNodeKey) && curNodeKey > -1)
            {
                umbraco.cms.businesslogic.CMSNode n = new umbraco.cms.businesslogic.CMSNode(curNodeKey);
                if (n.Id > -1)
                {
                    tree.id = n.ParentId;
                    tree.Render(ref xtree);//return all nodes from same level
                    xtree.treeCollection.RemoveAll(item => !item.NodeID.Equals(curNodeKey.ToString()));//render only one current node
                }
                else xtree.Add(tree.RootNode);
            }
            else xtree.Add(tree.RootNode);


            return xtree.ToString();
        }


        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            Authorize();
            StreamReader sr = new StreamReader(context.Request.InputStream);
            data d =sr.ReadToEnd().FromJson<data>();
            if (d == null)
            {
                d = new data()
                {
                    app = context.Request["app"],
                    treeType = context.Request["treeType"],
                    nodeKey = context.Request["nodeKey"]
                };
            }
            context.Response.ContentType = "application/json";
            context.Response.Write(GetInitAppTreeData(d));

        }


        public class data
        {
            public string app { get; set; }
            public string content { get; set; }
            public bool showContextMenu { get; set; }
            public bool isDialog { get; set; }
            public TreeDialogModes dialogMode { get; set; }
            public string treeType { get; set; }
            public string functionToCall { get; set; }
            public string dialogHandler { get; set; }
            public string nodeKey { get; set; }

        }
        #endregion
    }
}
